package com.dbky.alg.core.social.qq.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import org.apache.commons.lang3.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

/**
 * @Auther: tianchao
 * @Date: 2021/12/14 19:53
 * @Description:
 * https://graph.qq.com/user/get_user_info
 * https://graph.qq.com/user/get_user_info?
 * access_token=*************&
 * oauth_consumer_key=12345&
 * openid=****************
 * https://graph.qq.com/oauth2.0/me?access_token=YOUR_ACCESS_TOKEN
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {

    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    private static final String URL_GET_USER_INFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private String appId;

    private String openId;

    private ObjectMapper objectMapper = new ObjectMapper();

    public QQImpl(String accessToken,String appId){
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId = appId;
        String url = String.format(URL_GET_OPENID, accessToken);
        String result = getRestTemplate().getForObject(url,String.class);
        System.out.println(result);
        this.openId = StringUtils.substringBetween("\"openid:\"","}");
    }

    @Override
    public QQUserInfo getUserInfo()  {
        String url = String.format(URL_GET_USER_INFO,appId,openId);
        String result = getRestTemplate().getForObject(url, String.class);
        System.out.println(result);
        try {
            return objectMapper.readValue(result, QQUserInfo.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("获取用户信息失败");
        }

    }
}
